package com.platform.qujia.service.impl;

import com.alibaba.fastjson.JSON;
import com.platform.qujia.dao.*;
import com.platform.qujia.enums.CardRechargeRecordEnum;
import com.platform.qujia.dao.AppUserInfoMapper;
import com.platform.qujia.dao.FleetCardMapper;
import com.platform.qujia.dao.FleetCardSubMapper;
import com.platform.qujia.dao.OilMapper;
import com.platform.qujia.enums.WxTemplateEnum;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.FleetCardSubService;
import com.platform.qujia.service.PayOrderService;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FleetCardSubServiceImpl implements FleetCardSubService {
    private static Logger logger = (Logger) LoggerFactory.getLogger(FleetCardSubServiceImpl.class);
    @Resource
    private FleetCardSubMapper fleetCardSubMapper;

    @Resource
    private FleetCardMapper fleetCardMapper;

    @Resource
    private AppUserInfoMapper appUserInfoMapper;

    @Autowired
    private PayOrderService payOrderService;

    @Resource
    private WxPushUtil wxPushUtil;

    @Resource
    private OilMapper oilMapper;

    @Resource
    private FleetCardRechargeRecordMapper fleetCardRechargeRecordMapper;


    @Override
    public FleetCardSubVo selectFleetCardSub(Long enterpriseId, Integer userId) {
        return fleetCardSubMapper.selectFleetCardSub(enterpriseId, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FleetCardSubVo apply(FleetCardSubForm fleetCardSubForm) {
        FleetCardSubVo fleetCardSubVo = fleetCardSubMapper.selectFleetCardSub(fleetCardSubForm.getEnterpriseId(), fleetCardSubForm.getAppUserId());
        if (ObjectUtils.isNotEmpty(fleetCardSubVo)&&!fleetCardSubVo.getStatus().equals(FleetCardSubVo.NO_PASS)) throw new CustomException("已经申请，请勿重复操作！");

        /*FleetCardSub fleetCardSubQuery=new FleetCardSub();
        fleetCardSubQuery.setAppUserId(fleetCardSubForm.getAppUserId().longValue());

        List<FleetCardSubVo> list= fleetCardSubMapper.query(fleetCardSubQuery);
        if(list.size()>0){
            //用户已经加入车队
            throw new CustomException("用户已经加入车队,或在审核中");
        }*/
        AppUserInfo appUserById = appUserInfoMapper.getAppUserById(fleetCardSubForm.getAppUserId().longValue());
        FleetCard fleetCardQuery=new FleetCard();
        fleetCardQuery.setPhone(appUserById.getMobilePhone());
        fleetCardQuery.setEnterpriseId(fleetCardSubForm.getEnterpriseId());
        List<FleetCard> list= fleetCardMapper.query(fleetCardQuery);
        if(list.size()>0){
            throw new CustomException("该用户手机号已经创建了车队卡");
        }

//        // 查询车队下是否已经加了子卡，并且比对手机号
//        FleetCardSubVo cardSubVo = fleetCardSubMapper.selectFleetSubCardByFleetCardId(fleetCardSubForm.getFleetCardId());
//        if (null != cardSubVo && !appUserById.getMobilePhone().equals(cardSubVo.getPhone())) {
//            throw new CustomException("该车队已经创建了子卡！");
//        }

        FleetCardSub fleetCardSub = new FleetCardSub();
        BeanUtils.copyProperties(fleetCardSubForm, fleetCardSub);
        fleetCardSub.setAppUserId(Long.valueOf(fleetCardSubForm.getAppUserId()));
        fleetCardSub.setCardNumber("102" + System.currentTimeMillis()); // 前缀102代表车队子卡
//        // 用户还不是会员，就已经在pc端录入了车队信息，需要将金额整合
//        if (null != cardSubVo && appUserById.getMobilePhone().equals(cardSubVo.getPhone())) {
//            fleetCardSub.setBalance(cardSubVo.getBalance());
//            fleetCardSub.setSpendAmount(cardSubVo.getSpendAmount());
//        }
        // 信息需要落到子卡表（手机号和车牌号字段是新增的）
        fleetCardSub.setPhone(appUserById.getMobilePhone());
        fleetCardSub.setTruckNumber(fleetCardSubForm.getTruckNumber());
        fleetCardSubMapper.insertFleetCardSub(fleetCardSub);

        // 更新车牌
        if (StringUtils.isNotEmpty(fleetCardSubForm.getTruckNumber())) {
            AppUserInfo appUserInfo = new AppUserInfo();
            appUserInfo.setUserId(fleetCardSubForm.getAppUserId());
            appUserInfo.setEnterpriseId(Integer.valueOf(fleetCardSubForm.getEnterpriseId().toString()));
            appUserInfo.setTruckNumber(fleetCardSubForm.getTruckNumber());
            appUserInfoMapper.updateAppUserInfoByUserId(appUserInfo);
        }
        return fleetCardSubMapper.selectFleetCardSub(fleetCardSubForm.getEnterpriseId(), fleetCardSubForm.getAppUserId());
    }

    @Override
    public int unbind(Long id) {
        FleetCardSubVo fleetCardSubVo = fleetCardSubMapper.selectFleetCardSubById(id);
        if (ObjectUtils.isEmpty(fleetCardSubVo)) return 0;

        if (fleetCardSubVo.getBalanceSub().compareTo(BigDecimal.ZERO) > 0)
            throw new CustomException("子卡存在额度，不可解绑！");

        FleetCardSub fleetCardSub = new FleetCardSub();
        fleetCardSub.setId(id);
        fleetCardSub.setDel(System.currentTimeMillis());
        fleetCardSub.setUpdatedTime(new Date());
        return fleetCardSubMapper.updateFleetCardSub(fleetCardSub);
    }

    @Override
    public FleetCardSubVo selectOneFleetCardSub(Long enterpriseId, Integer userId) {
        return fleetCardSubMapper.selectOneFleetCardSub(enterpriseId,userId);
    }

    @Override
    public FleetCardSubVo selectFleetSubCardByCardNumber(String cardNumber) {
        return fleetCardSubMapper.selectFleetSubCardByCardNumber(cardNumber);
    }

    @Override
    public PayOrder cdkSubPay(FleetCardSubVo fleetCardSub, Station station,PayOrder payOrder) {
        BigDecimal orderAmt = BigDecimal.valueOf(payOrder.getAmt());
        if (ObjectUtils.notEqual(fleetCardSub.getEnterpriseId(), Long.valueOf(station.getEnterpriseId())))
            throw new CustomException("该车队卡不归属于该油企/油站", 1001);
        if (fleetCardSub.getBalance().compareTo(orderAmt) < 0)
            throw new CustomException("该车队卡余额不足", 1001);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        FleetCardSub updateFleetCardSub = new FleetCardSub();
        updateFleetCardSub.setId(fleetCardSub.getId());
        updateFleetCardSub.setBalance(fleetCardSub.getBalance().subtract(orderAmt));
        updateFleetCardSub.setUpdatedTime(new Date());
        FleetCardSubVo fleetCardSubVo = fleetCardSubMapper.selectFleetCardSubById(fleetCardSub.getId());
        BigDecimal spendAmount = BigDecimal.ZERO;
        if(fleetCardSubVo!=null&&fleetCardSubVo.getSpendAmount()!=null){
            spendAmount = fleetCardSubVo.getSpendAmount();
        }
        updateFleetCardSub.setSpendAmount(spendAmount.add(orderAmt));
        updateFleetCardSub(updateFleetCardSub);

        payOrder.setCdkType(FleetCard.cdkType_fleet_card_sub);
        payOrder.setConsumer(fleetCardSub.getFleetName());       //客户昵称
        if(fleetCardSub.getAppUserId()!=null){
            AppUserInfo appUserInfo=appUserInfoMapper.getAppUserById(fleetCardSub.getAppUserId());
            if(appUserInfo!=null){
                payOrder.setCustomerPhone(appUserInfo.getMobilePhone());
            }
        }
        payOrder.setConsumerId(fleetCardSub.getAppUserId().intValue());// 用户id
        payOrder.setCdkId(fleetCardSub.getId());// 车队卡id

        payOrder.setEnterpriseName(station.getEnterprise().getEnterpriseName());
        payOrder.setBalance(updateFleetCardSub.getBalance()); // 保存车队卡余额
        gzhPaySuccessPush(fleetCardSubVo,updateFleetCardSub,payOrder);
        fleetCardRechargeRecord(fleetCardSubVo,payOrder,updateFleetCardSub);
        return payOrder;
    }

    // 生成车队卡子卡消费记录
    private void fleetCardRechargeRecord(FleetCardSubVo fleetCardSubVo, PayOrder payOrder, FleetCardSub updateFleetCardSub){
        FleetCardRechargeRecord fleetCardRechargeRecord = new FleetCardRechargeRecord();
        fleetCardRechargeRecord.setEnterpriseId(fleetCardSubVo.getEnterpriseId());
        fleetCardRechargeRecord.setFleetCardId(fleetCardSubVo.getFleetCardId());
        fleetCardRechargeRecord.setFleetCardSubId(fleetCardSubVo.getId());
        // 消费金额
        fleetCardRechargeRecord.setRechargeAmount(BigDecimal.valueOf(payOrder.getAmt()));
        fleetCardRechargeRecord.setGiftAmount(BigDecimal.ZERO);
        fleetCardRechargeRecord.setBalance(fleetCardSubVo.getBalance());
        fleetCardRechargeRecord.setAfterBalance(updateFleetCardSub.getBalance());
        fleetCardRechargeRecord.setCreatedTime(new Date());
        fleetCardRechargeRecord.setStationId(payOrder.getStationId().longValue());
        fleetCardRechargeRecord.setCardType(CardRechargeRecordEnum.CONSUMPTION_XF.getValue());
        fleetCardRechargeRecord.setFleetOrderNo(payOrder.getOrderNo());
        fleetCardRechargeRecord.setOilId(Long.valueOf(payOrder.getOilName()));

        fleetCardRechargeRecord.setUserName(fleetCardSubVo.getName());
        AppUserInfo appUser = appUserInfoMapper.getAppUserById(fleetCardSubVo.getAppUserId());
        fleetCardRechargeRecord.setUserPhone(appUser.getMobilePhone());
        fleetCardRechargeRecordMapper.insertSelective(fleetCardRechargeRecord);

    }


    public void gzhPaySuccessPush(FleetCardSubVo fleetCardSubVo,FleetCardSub updateFleetCardSub,PayOrder payOrder){
        AppUserInfo appUserInfo = appUserInfoMapper.selectAppUserInfoById(fleetCardSubVo.getAppUserId());
        FleetCard fleetCard = fleetCardMapper.selectById(fleetCardSubVo.getFleetCardId());
        AppUserInfo info=new AppUserInfo();
        info.setMobilePhone(fleetCard.getPhone());
        info.setStationId(fleetCard.getEnterpriseId().intValue());
        List<AppUserInfo> appUserInfos = appUserInfoMapper.selectAppUserInfoByMobilePhoneAndStationId(info);


        if(appUserInfo != null){
            Map<String, String> templateParams = new HashMap<>();
            templateParams.put("openid", appUserInfo.getBlogOpenid());
            String string = payOrder.getStationName() + ",持卡人:" + fleetCardSubVo.getName();
            if(string.length() > 20){
                string = string.substring(0,17) + "...";
            }
            templateParams.put("stationName", string);
            templateParams.put("oilName", payOrder.getOilName());
            if(StringUtils.isNotEmpty(payOrder.getOilName())){
                Oil oil = oilMapper.selectOilById(Long.valueOf(payOrder.getOilName()));
                templateParams.put("oilName", oil.getOilName());
            }
            templateParams.put("payDetail", "实付" + payOrder.getAmt() + "元"+",优惠"+payOrder.getDiscountAmt()+"元");
            templateParams.put("walletBalance", updateFleetCardSub.getBalance().toString() + "元");
            logger.info("车队卡支付-微信模板参数：{}", templateParams);
            wxPushUtil.sendTemplateMsg(payOrder.getEnterpriseId(), templateParams, WxTemplateEnum.REFUEL_SUCCESS);
            if(appUserInfos.size()>0){
                AppUserInfo appUserInfo1 = appUserInfos.get(0);
                //templateParams.put("openid", appUserInfo1.getBlogOpenid());
                Map<String,String> map = JSON.parseObject(JSON.toJSONString(templateParams), HashMap.class);
                map.put("openid",appUserInfo1.getBlogOpenid());
                logger.info("车队卡支付-微信模板参数：{}", map);
                wxPushUtil.sendTemplateMsg(payOrder.getEnterpriseId(), map, WxTemplateEnum.REFUEL_SUCCESS);
            }
        }
    }

    private int updateFleetCardSub(FleetCardSub updateFleetCardSub) {
        return fleetCardSubMapper.updateFleetCardSub(updateFleetCardSub);
    }
}
